import { reqGetCode, reqUserRegister, reqUserLogin, reqUserInfo, reqLogout } from "@/api"
import { setToken, getToken, removeToken } from '../util/token';
// 仓库存储数据
const state = {
  code: '',
  token: getToken(),
  userinfo: {}
}
// 修改state的唯一手段
const mutations = {
  GETCODE(state, code) {
    state.code = code
  },
  USERLOGIN(state, token) {
    state.token = token 
  },
  USERINFO(state,userinfo) {
    state.userinfo = userinfo
  },
  LOGOUT(state) {
    state.token = '',
    state.userinfo = {},
    removeToken()
  }
}
// 处理action，可以书写自己的业务逻辑，也可以处理异步
const actions = {
  async getCode({commit},phone) {
    let result = await reqGetCode(phone)
    if(result.code == 200) {
      commit('GETCODE', result.data)
      return 'ok'
    }else {
      return Promise.reject(new Error('faile'))
    }
  },
  async userRegister({commit}, user) {
    let result = await reqUserRegister(user)
    if (result.code == 200) {
      return 'ok';
    } else {
      return Promise.reject(new Error('faile'));
    }
  },
  async userLogin({commit}, data) {
    let result = await reqUserLogin(data)
    if(result.code == 200) {
      commit('USERLOGIN', result.data.token)
      // 持久化存储token
      setToken(result.data.token)
    }else {
      return Promise.reject(new error('faile'))
    }
  },
  async getUserInfo({commit}) {
    let result = await reqUserInfo()
    // console.log(result);
    if(result.code == 200) {
      commit('USERINFO', result.data)
    }
  },
  async logout({commit}) {
    let result = await reqLogout()
    if(result.code == 200) {
      commit('LOGOUT')
      return 'ok'
    }else {
      return Promise.reject(new Error('faile'))
    }
  }

}
// 类似于计算属性
const getters = {


}

export default {
  state,
  mutations,
  actions,
  getters
}